{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <style>
        /* dataTables列内容居中 */
        #asset_idc > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #asset_idc > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        /* dataTables列内容居中 */
        #asset_cabinet > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #asset_cabinet > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        /* dataTables列内容居中 */
        #asset_provider > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #asset_provider > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        .form-horizontal .form-group {
            margin-right: -200px;
        }

        .has-select-error {
            border: 1px solid red;
        }
    </style>
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
{% endblock %}

{% block content %}

    <div class="row">
        <!-- Custom Tabs -->
        <div class="nav-tabs-custom">
            <ul class="nav nav-tabs">
                <li class="active"><a href="#tab_1" data-toggle="tab">机房列表</a></li>
                <li><a href="#tab_2" data-toggle="tab">机柜列表</a></li>
                <li><a href="#tab_3" data-toggle="tab">供应商列表</a></li>
            </ul>
            <div class="tab-content" style="padding: 0">
                <div class="tab-pane active" id="tab_1">
                    {% include 'assets/idc_list.html' %}
                </div>
                <!-- /.tab-pane -->
                <div class="tab-pane" id="tab_2">
                    {% include 'assets/cabinet_list.html' %}
                </div>
                <!-- /.tab-pane -->
                <div class="tab-pane" id="tab_3">
                    {% include 'assets/provider_list.html' %}
                </div>
                <!-- /.tab-pane -->
            </div>
            <!-- /.tab-content -->
        </div>
        <!-- nav-tabs-custom -->
    </div>
    <!-- /.row -->

{% endblock %}


{% block js %}
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <!-- DataTables -->
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>

    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>

    <script>
        language = {
                   "sProcessing": "处理中...",
                   "sLengthMenu": "显示 _MENU_ 项结果",
                   "sZeroRecords": "没有匹配结果",
                   "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                   "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                   "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                   "sInfoPostFix": "",
                   "sSearch": "搜索:",
                   "sUrl": "",
                   "sEmptyTable": "表中数据为空",
                   "sLoadingRecords": "载入中...",
                   "sInfoThousands": ",",
                   "oPaginate": {
                       "sFirst": "首页",
                       "sPrevious": "上页",
                       "sNext": "下页",
                       "sLast": "末页"
                   },
                   "oAria": {
                       "sSortAscending": ": 以升序排列此列",
                       "sSortDescending": ": 以降序排列此列"
                   }
               }

        $(function () {
            idc_table = $('#asset_idc').DataTable({
                language: language,
                columnDefs: [{
                    'targets': [-1],
                    'orderable': false
                }],
                "order": [[0, "asc"]]
            });

            cabinet_table = $('#asset_cabinet').DataTable({
                language: language,
                columnDefs: [{
                    'targets': [-1],
                    'orderable': false
                }],
                "order": [[0, "asc"]]
            });

            provider_table = $('#asset_provider').DataTable({
                language: language,
                columnDefs: [{
                    'targets': [-1],
                    'orderable': false
                }],
                "order": [[0, "asc"]]
            });

            $('#idc').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
            });
        });

        function addErrorMessage(errors) {
            $.each(errors, function(name, value){
                $.each(value, function(i, v){
                    $('#'+name).after('<span class="help-block">'+v+'</span>')
                })
                $('#'+name).parent().parent().addClass('has-error')
            })
        }

        function clearErrorMessage(){
            $('.help-block').remove()
            $('.form-group').removeClass('has-error')
        }

        <!-- 机房操作 -->
        let idc_tbody = $('#asset_idc tbody');
        let idc_ops = $('#idc_ops');

        // 添加机房
        $('#add-idc').on('click', function () {
            document.getElementById('idc_info').reset();
            $('.modal-title').text('新增机房');
            idc_ops.text('添加');
            clearErrorMessage();
            idc_ops.unbind('click').on('click', function () {
                clearErrorMessage();
                let data = $('#idc_info').serializeJson();
                $.ajax({
                    url: '/api/idc/',
                    type: 'POST',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        $('#IDCModal').modal('hide');
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '新增成功！',
                        });
                        idc_table.row.add([
                            res.id,
                            res.idc_name,
                            res.idc_address,
                            res.idc_contact,
                            res.idc_telephone,
                            '',
                            res.idc_memo,
                            `<button type="button" class="btn btn-success btn-xs modify" data-toggle="modal" data-id="${res.id}" data-target="#IDCModal">修改</button> <button type="button" class="btn btn-danger btn-xs delete" data-id="${res.id}">删除</button>`
                        ]).draw();
                    },
                    error: function (response) {
                        errors = JSON.parse(response.responseText)
                        addErrorMessage(errors)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误信息',
                        });
                    }
                })
            })
        });

        // 更新机房
        idc_tbody.on('click', '.modify', function () {
            let idc_id = $(this).attr('data-id');
            let idc_td_obj = $(this).parents('tr').children();
            $('.modal-title').text('修改机房信息');
            idc_ops.text('确认修改');
            var initial1 = idc_td_obj[1].innerText
            $('#idc_name').val(initial1);
            $('#idc_address').val(idc_td_obj[2].innerText);
            $('#idc_contact').val(idc_td_obj[3].innerText);
            $('#idc_telephone').val(idc_td_obj[4].innerText);
            $('#idc_memo').val(idc_td_obj[6].innerText);
            clearErrorMessage();
            idc_ops.unbind('click').on('click', function () {
                clearErrorMessage();
                let data = $('#idc_info').serializeJson();
                $.ajax({
                    url: '/api/idc/' + idc_id + '/',
                    type: 'PUT',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        $('#IDCModal').modal('hide');
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '修改成功！',
                            buttons: {
                                   ok: function () {
                                       if(idc_td_obj[5].innerText.trim() && initial1 != res.idc_name){
                                         window.location.reload()
                                    }
                                },
                            },
                        });
                        idc_td_obj[1].innerText = res.idc_name;
                        idc_td_obj[2].innerText = res.idc_address;
                        idc_td_obj[3].innerText = res.idc_contact;
                        idc_td_obj[4].innerText = res.idc_telephone;
                        idc_td_obj[6].innerText = res.idc_memo;
                    },
                    error: function (response) {
                        errors = JSON.parse(response.responseText)
                        addErrorMessage(errors)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误信息',
                        });
                    }
                })
            });
        });

        // 删除机房
        idc_tbody.on('click', '.delete', function () {
            let pk = $(this).attr('data-id');
            let tr_obj = $(this).parents('tr');
            {% if perms.assets.delete_idc %}
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/api/idc/' + pk + '/',
                                method: 'DELETE',
                                success: function () {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'green',
                                        content: '删除成功！',
                                        buttons: {
                                               ok: function () {
                                                   if(tr_obj.children()[5].innerText.trim()){
                                                        window.location.reload()
                                                    }
                                            },
                                        },
                                    });
                                    idc_table.row(tr_obj).remove().draw();
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除机房的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });


        <!-- 机柜操作 -->
        let cabinet_tbody = $('#asset_cabinet tbody');
        let cabinet_ops = $('#cabinet_ops');

        // 添加机柜
        $('#add-cabinet').on('click', function () {
            document.getElementById('cabinet_info').reset();
            {#$(".select2").val('').trigger('change');#}
            idcSelector();
            $('.modal-title').text('新增机柜');
            cabinet_ops.text('添加');
            clearErrorMessage();
            $('#idc+div>.selectize-input').removeClass('has-select-error')
            cabinet_ops.unbind('click').on('click', function () {
                let data = $('#cabinet_info').serializeJson();
                let idc_name = $('#idc option:selected').text();
                clearErrorMessage();
                $('#idc+div>.selectize-input').removeClass('has-select-error')
                $.ajax({
                    url: '/api/cabinet/',
                    type: 'POST',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        $('#CabinetModal').modal('hide');
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '新增成功！',
                            buttons: {
                                   ok: function () {
                                       window.location.reload()
                                },
                            },
                        });
                    },
                    error: function (response) {
                        errors = JSON.parse(response.responseText)
                        if(errors.hasOwnProperty('idc')){
                            $('#idc').parent().parent().addClass('has-error')
                            $('#idc+div>.selectize-input').addClass('has-select-error')
                            $('#idc+div>.selectize-input').after('<span class="help-block">'+errors.idc+'</span>')
                            delete errors.idc
                        }
                        addErrorMessage(errors)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误信息',
                        });
                    }
                })
            })
        });

        // 更新机柜
        cabinet_tbody.on('click', '.modify', function () {
            let select_obj = idcSelector();
            let cabinet_id = $(this).attr('data-id');
            let idc_id = $(this).attr('data-idc');
            let cabinet_td_obj = $(this).parents('tr').children();
            $('.modal-title').text('修改机柜信息');
            cabinet_ops.text('确认修改');
            var initial1 = cabinet_td_obj[1].innerText
            $('#cabinet_name').val(initial1);
            var initial2 = cabinet_td_obj[2].innerText;
            select_obj.setValue(idc_id)
            $('#cabinet_memo').val(cabinet_td_obj[4].innerText);
            clearErrorMessage();
            $('#idc+div>.selectize-input').removeClass('has-select-error')
            cabinet_ops.unbind('click').on('click', function () {
                let data = $('#cabinet_info').serializeJson();
                let idc_name = $('#idc').find(':selected').text();
                clearErrorMessage();
                $('#idc+div>.selectize-input').removeClass('has-select-error')
                $.ajax({
                    url: '/api/cabinet/' + cabinet_id + '/',
                    type: 'PUT',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        $('#CabinetModal').modal('hide');
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '修改成功！',
                            buttons: {
                                   ok: function () {
                                       if(res.cabinet_name != initial1 || idc_name != initial2){
                                          window.location.reload()
                                    }
                                },
                            },
                        });
                        cabinet_td_obj[5].children[0].setAttribute('data-idc',res.idc)
                        cabinet_td_obj[1].innerText = res.cabinet_name;
                        cabinet_td_obj[2].innerText = idc_name;
                        cabinet_td_obj[4].innerText = res.cabinet_memo;
                    },
                    error: function (response) {
                        errors = JSON.parse(response.responseText)
                        if(errors.hasOwnProperty('idc')){
                            $('#idc').parent().parent().addClass('has-error')
                            $('#idc+div>.selectize-input').addClass('has-select-error')
                            $('#idc+div>.selectize-input').after('<span class="help-block">'+errors.idc+'</span>')
                            delete errors.idc
                        }
                        addErrorMessage(errors)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误信息',
                        });
                    }
                })
            });
        });

        // 删除机柜
        cabinet_tbody.on('click', '.delete', function () {
            let pk = $(this).attr('data-id');
            let tr_obj = $(this).parents('tr');

            {% if perms.assets.delete_cabinet %}
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/api/cabinet/' + pk + '/',
                                method: 'DELETE',
                                success: function () {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'green',
                                        content: '删除成功！',
                                        buttons: {
                                               ok: function () {
                                                   window.location.reload()
                                            },
                                        },
                                    });
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除机柜的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });


        <!-- 供应商操作 -->
        let provider_tbody = $('#asset_provider tbody');
        let provider_ops = $('#provider_ops');

        // 添加供应商
        $('#add-provider').on('click', function () {
            document.getElementById('provider_info').reset();
            $('.modal-title').text('新增供应商');
            provider_ops.text('添加');
            clearErrorMessage();
            provider_ops.unbind('click').on('click', function () {
                let data = $('#provider_info').serializeJson();
                clearErrorMessage();
                $.ajax({
                    url: '/api/asset_provider/',
                    type: 'POST',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        $('#ProviderModal').modal('hide');
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '新增成功！',
                        });
                        provider_table.row.add([
                            res.id,
                            res.asset_provider_name,
                            res.asset_provider_contact,
                            res.asset_provider_telephone,
                            res.asset_provider_memo,
                            `<button type="button" class="btn btn-success btn-xs modify" data-toggle="modal" data-id="${res.id}" data-target="#ProviderModal">修改</button> <button type="button" class="btn btn-danger btn-xs delete" data-id="${res.id}">删除</button>`
                        ]).draw();
                    },
                    error: function (response) {
                        errors = JSON.parse(response.responseText)
                        addErrorMessage(errors)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误信息',
                        });
                    }
                })
            })
        });

        // 更新供应商
        provider_tbody.on('click', '.modify', function () {
            let provider_id = $(this).attr('data-id');
            let provider_td_obj = $(this).parents('tr').children();
            $('.modal-title').text('修改供应商信息');
            provider_ops.text('确认修改');
            $('#asset_provider_name').val(provider_td_obj[1].innerText);
            $('#asset_provider_contact').val(provider_td_obj[2].innerText);
            $('#asset_provider_telephone').val(provider_td_obj[3].innerText);
            $('#asset_provider_memo').val(provider_td_obj[4].innerText);
            clearErrorMessage();
            provider_ops.unbind('click').on('click', function () {
                let data = $('#provider_info').serializeJson();
                clearErrorMessage();
                $.ajax({
                    url: '/api/asset_provider/' + provider_id + '/',
                    type: 'PUT',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        $('#ProviderModal').modal('hide');
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: '修改成功！',
                        })
                        provider_td_obj[1].innerText = res.asset_provider_name;
                        provider_td_obj[2].innerText = res.asset_provider_contact;
                        provider_td_obj[3].innerText = res.asset_provider_telephone;
                        provider_td_obj[4].innerText = res.asset_provider_memo;
                    },
                    error: function (response) {
                        errors = JSON.parse(response.responseText)
                        addErrorMessage(errors)
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '请修改错误信息',
                        });
                    }
                })
            });
        });

        // 删除供应商
        provider_tbody.on('click', '.delete', function () {
            let pk = $(this).attr('data-id');
            let tr_obj = $(this).parents('tr');

            {% if perms.assets.delete_assetprovider %}
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/api/asset_provider/' + pk + '/',
                                method: 'DELETE',
                                success: function () {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'green',
                                        content: '删除成功！',
                                    });
                                    provider_table.row(tr_obj).remove().draw();
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除供应商的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 将数据JSON化
        (function ($) {
            $.fn.serializeJson = function () {
                let serializeObj = {};
                let array = this.serializeArray();
                $(array).each(function () {
                    if (serializeObj[this.name]) {
                        if ($.isArray(serializeObj[this.name])) {
                            serializeObj[this.name].push(this.value);
                        } else {
                            serializeObj[this.name] = [serializeObj[this.name], this.value];
                        }
                    } else {
                        serializeObj[this.name] = this.value;
                    }
                });
                return serializeObj;
            };
        })(jQuery);
    </script>

{% endblock %}

